package com.example.spring_boot_demo.schedule;

import com.example.spring_boot_demo.controller.CategoryController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

//@Component
@EnableScheduling
@EnableAsync
public class SpringScheduleTask {

    private static final Logger log = LoggerFactory.getLogger(SpringScheduleTask.class);

    //每3秒执行一次
    //@Scheduled(fixedRate = 3000)
    //public void notifyAByFixed3s(){
    //    String now = new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date());
    //    String name = Thread.currentThread().getName();
    //    log.info("{} 发送通知，发送时间为：{}",name,now);
    //}

    ////每2秒执行一次
    //@Scheduled(fixedRate = 2000)
    //public void notifyAByFixed2s(){
    //    String now = new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date());
    //    String name = Thread.currentThread().getName();
    //    log.info("{} 发送通知，发送时间为：{}",name,now);
    //}

    /**
     * 模拟任务阻塞4s，每2秒执行一次
     *  当前这个定时任务执行，会在上一个定时任务执行完后，直接开始执行
    */
    //@Scheduled(fixedRate = 2000)
    //public void notifyAByFixed2s() throws InterruptedException {
    //    Thread.sleep(4000);
    //    String now = new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date());
    //    String name = Thread.currentThread().getName();
    //    log.info("{} 发送通知，发送时间为：{}",name,now);
    //}

    /**
     * 每2秒执行一次,并延迟2s
     * 当前这个定时任务，会在上一个定时任务执行完后，延迟2s才执行
    */
    //@Scheduled(fixedDelay = 2000)
    //public void notifyB() throws InterruptedException {
    //    Thread.sleep(4000);
    //    String now = new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date());
    //    String name = Thread.currentThread().getName();
    //    log.info("{} 发送通知，发送时间为：{}",name,now);
    //}





    //每2秒执行一次
    @Async
    @Scheduled(cron = "0/2 * * * * ?")
    public void notifyA() throws InterruptedException {
        Thread.sleep(4000);
        String now = new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date());
        String name = Thread.currentThread().getName();
        log.info("notifyA {} 发送通知，发送时间为：{}",name,now);
    }


    //每3秒执行一次
    @Async
    @Scheduled(cron = "0/3 * * * * ?")
    public void notifyB() throws InterruptedException {
        String now = new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date());
        String name = Thread.currentThread().getName();
        log.info("notifyB {} 发送通知，发送时间为：{}",name,now);
    }
}

